﻿using System.Collections.Generic;
using System.IO;

namespace Pvf.Core.Converters
{
    internal sealed class PvfStringConverter : PvfBinaryConverter<string>
    {
        public override bool CanRead(BinaryReader reader)
        {
            var peek = reader.PeekChar();
            return peek == 5 || peek == 6 || peek == 7 || peek == 8 || peek == 10;
        }

        public override string Deserialize(BinaryReader reader, IPvfModule module = null)
        {
            var c = reader.PeekChar();

            TypeCheck(reader, 5, 6, 7, 8, 10);

            var key = reader.ReadInt32();

            if (!Layout.Env.StringTable.TryGetValue(key, out var foundValue))
            {
                throw new KeyNotFoundException($"字符串键未在StringTable中找到:{foundValue}");
            }

            if (c == 10 && module != null && module.Strings != null)
            {
                if (module.Strings.TryGetValue(foundValue, out var finalValue))
                {
                    return finalValue;
                }
            }

            return foundValue;
        }
    }
}
